<template>
  <div class="account-configuration-container">
    <ContentWrap class="account-wrapper">
      <!-- 账号配置头部 -->
      <div class="account-header">
        <div class="header-left">
          <div class="header-icon">
            <Icon icon="ep:avatar" />
          </div>
          <div class="header-content">
            <h4 class="account-title">用户配置</h4>
            <p class="account-subtitle">管理租户的用户账号信息</p>
          </div>
        </div>
        <el-button type="primary" @click="addConfigura" class="add-btn">
          <Icon icon="ep:plus" class="btn-icon" />
          新增
        </el-button>
      </div>

      <!-- 表格容器 -->
      <div class="table-container">
        <el-table
          v-loading="loading"
          :data="list"
          class="enhanced-table"
          :header-cell-style="{ background: '#f8f9ff', color: '#303133', fontWeight: '600' }"
        >
          <el-table-column
            label="登录账号"
            align="center"
            prop="username"
            :show-overflow-tooltip="true"
          >
            <template #default="scope">
              <div class="username-cell">
                <Icon icon="ep:user" class="username-icon" />
                <span class="username-text">{{ scope.row.username }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            label="用户昵称"
            align="center"
            prop="nickname"
            :show-overflow-tooltip="true"
          >
            <template #default="scope">
              <div class="nickname-cell">
                <Icon icon="ep:avatar" class="nickname-icon" />
                <span class="nickname-text">{{ scope.row.nickname }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            label="部门"
            align="center"
            key="deptName"
            prop="deptName"
            :show-overflow-tooltip="true"
          >
            <template #default="scope">
              <div class="dept-cell">
                <Icon icon="ep:office-building" class="dept-icon" />
                <span class="dept-text">{{ scope.row.deptName || '-' }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="手机号码" align="center" prop="mobile" width="160">
            <template #default="scope">
              <div class="mobile-cell">
                <Icon icon="ep:phone" class="mobile-icon" />
                <span class="mobile-text">{{ scope.row.mobile || '-' }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="状态" key="status" width="100">
            <template #default="scope">
              <div class="status-cell">
                <el-switch
                  v-model="scope.row.status"
                  :active-value="0"
                  :inactive-value="1"
                  @change="handleStatusChange(scope.row)"
                />
              </div>
            </template>
          </el-table-column>

          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
            width="200"
          >
            <template #default="scope">
              <div class="time-cell">
                <Icon icon="ep:clock" class="time-icon" />
                <span>{{ dateFormatter(scope.row, null, scope.row.createTime) }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="250" fixed="right">
            <template #default="scope">
              <div class="action-buttons">
                <el-button
                  type="primary"
                  link
                  @click="openForm('update', scope.row.id)"
                  class="action-btn edit-btn"
                  size="small"
                >
                  <Icon icon="ep:edit" class="btn-icon" />
                  修改
                </el-button>

                <el-dropdown
                  class="action-dropdown"
                  @command="(command) => handleCommand(command, scope.row)"
                >
                  <el-button type="primary" link class="action-btn more-btn" size="small">
                    <Icon icon="ep:d-arrow-right" class="btn-icon" />
                    更多
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu class="enhanced-dropdown">
                      <el-dropdown-item command="handleResetPwd" class="dropdown-item">
                        <Icon icon="ep:key" class="dropdown-icon" />
                        重置密码
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </ContentWrap>

    <!-- 新增 -->
    <UserForm ref="formRef" @success="getList" />
    <!-- 编辑 -->
    <OldUserFrom ref="formOldRef" @success="getList" :configureId="configureId" />
    <!-- 分配角色 -->
    <UserAssignRoleForm ref="assignRoleFormRef" @success="getList" />
  </div>
</template>

<script setup>
import { dateFormatter } from '@/utils/formatTime'
import * as TenantAccountApi from '@/api/system/tenantAccount'
import * as TenantApi from '@/api/system/tenant'
import * as UserApi from '@/api/system/user'
import { CommonStatusEnum } from '@/utils/constants'
import UserForm from './userFrom.vue'
import { checkPermi } from '@/utils/permission'
import OldUserFrom from '@/views/system/user/UserForm2.vue'
import UserAssignRoleForm from '@/views/system/user/UserAssignRoleForm.vue'

const message = useMessage()
const { t } = useI18n() // 国际化

const loading = ref(false)
const list = ref([])
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  tenantId: null
})
const bindRes = ref({})

// 获取list
const getList = async () => {
  loading.value = true
  try {
    const data = await UserApi.getUserPageByAdmin(queryParams)
    list.value = data.list
    const ids = []
    list.value.map((i) => {
      ids.push(i.id)
    })
    // bindRes.value = await UserApi.getBindStatus(ids)
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const props = defineProps({
  configureId: String
})

const handleQwBind = async (id, nickname) => {
  const data = await UserApi.getAuthUrlByUser(id)
  ElMessageBox.confirm(
    `请通知"${nickname}"的账户自行使用企微扫码或打开授权链接进行绑定`,
    '企微员工绑定提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      closeOnClickModal: false
    }
  )
    .then(() => {
      window.open(data)
    })
    .catch(() => {})
}

/** 修改用户状态 */
const handleStatusChange = async (row) => {
  try {
    // 修改状态的二次确认
    const text = row.status === CommonStatusEnum.ENABLE ? '启用' : '停用'
    await message.confirm('确认要"' + text + '""' + row.username + '"用户吗?')
    // 发起修改状态
    await UserApi.updateUserStatus(row.id, row.status)
    // 刷新列表
    await getList()
  } catch {
    // 取消后，进行恢复按钮
    row.status =
      row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.DISABLE : CommonStatusEnum.ENABLE
  }
}

const formRef = ref(null)
/*新增*/
const addConfigura = () => {
  formRef.value.open('create', queryParams.tenantId)
}

/*修改*/
const formOldRef = ref(null)
const openForm = (type, id, row) => {
  // formRef.value.open('update', queryParams.tenantId, id)
  formOldRef.value.open(type, queryParams.tenantId, id)
}

/** 分配角色 */
const assignRoleFormRef = ref()
const handleRole = (row) => {
  assignRoleFormRef.value.open(row)
}

/** 操作分发 */
const handleCommand = (command, row) => {
  switch (command) {
    case 'handleDelete':
      handleDelete(row.id)
      break
    case 'handleResetPwd':
      handleResetPwd(row)
      break
    default:
      break
  }
}

/** 删除按钮操作 */
const handleDelete = async (id) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await UserApi.delByAdmin({ tenantId: queryParams.tenantId, id })
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 重置密码 */
const handleResetPwd = async (row) => {
  try {
    // 重置的二次确认
    const result = await message.prompt(
      '请输入"' + row.username + '"的新密码',
      t('common.reminder')
    )
    const password = result.value
    // 发起重置
    await UserApi.resetUserPwd(row.id, password)
    message.success('修改成功，新密码是：' + password)
  } catch {}
}

watch(
  () => props.configureId,
  (value) => {
    queryParams.tenantId = value
    getList()
  },
  { immediate: true, deep: true }
)
</script>

<style lang="scss" scoped>
// 主题色变量
$primary-color: #0052cc;
$primary-light: rgba(0, 82, 204, 0.1);
$primary-border: rgba(0, 82, 204, 0.3);
$success-color: #67c23a;
$warning-color: #e6a23c;
$danger-color: #f56c6c;
$info-color: #909399;
$text-primary: #303133;
$text-regular: #606266;
$text-secondary: #909399;
$text-placeholder: #c0c4cc;
$border-color: #dcdfe6;
$border-light: #e4e7ed;
$bg-color: #f5f7fa;
$shadow-light: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
$shadow-base:
  0 2px 4px rgba(0, 0, 0, 0.12),
  0 0 6px rgba(0, 0, 0, 0.04);
$border-radius: 12px;
$border-radius-small: 8px;

.account-configuration-container {
  padding: 0;
}

.account-wrapper {
  border-radius: $border-radius;
  overflow: hidden;
  box-shadow: $shadow-light;
  border: 1px solid $border-light;

  :deep(.el-card__body) {
    padding: 0;
  }
}

/* 账号配置头部 */
.account-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: linear-gradient(135deg, $primary-color 0%, #1d4ed8 100%);
  color: white;
  border-bottom: 1px solid $border-light;

  @media (max-width: 768px) {
    padding: 16px;
    flex-direction: column;
    gap: 16px;
  }
}

.header-left {
  display: flex;
  align-items: center;
  flex: 1;

  @media (max-width: 768px) {
    justify-content: center;
    text-align: center;
  }
}

.header-icon {
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: $border-radius-small;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  flex-shrink: 0;

  @media (max-width: 768px) {
    width: 36px;
    height: 36px;
    font-size: 16px;
  }
}

.header-content {
  margin-left: 12px;

  @media (max-width: 768px) {
    margin-left: 10px;
  }
}

.account-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 4px 0;

  @media (max-width: 768px) {
    font-size: 16px;
  }
}

.account-subtitle {
  font-size: 13px;
  opacity: 0.9;
  margin: 0;

  @media (max-width: 768px) {
    font-size: 12px;
  }
}

.add-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 2px solid rgba(255, 255, 255, 0.3);
  color: white;
  border-radius: $border-radius-small;
  padding: 10px 20px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;

  &:hover {
    background: white;
    color: $primary-color;
    border-color: white;
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(255, 255, 255, 0.3);
  }

  @media (max-width: 768px) {
    width: 100%;
    justify-content: center;
  }

  .btn-icon {
    font-size: 14px;
  }
}

/* 表格容器 */
.table-container {
  background: white;
  overflow-x: auto;
}

.enhanced-table {
  :deep(.el-table__header) {
    th {
      background: linear-gradient(135deg, #f8f9ff 0%, #f0f2ff 100%) !important;
      color: $text-primary !important;
      font-weight: 600 !important;
      border-bottom: 2px solid $primary-light;
      padding: 16px 12px;
    }
  }

  :deep(.el-table__body) {
    tr {
      transition: all 0.3s ease;

      &:hover {
        background: $primary-light !important;
      }

      td {
        padding: 14px 12px;
        border-bottom: 1px solid $border-light;
      }
    }

    .el-table__row--striped {
      background: #fafbff;

      &:hover {
        background: $primary-light !important;
      }
    }
  }

  // H5适配
  @media (max-width: 768px) {
    :deep(.el-table__header) th {
      padding: 12px 8px;
      font-size: 13px;
    }

    :deep(.el-table__body) td {
      padding: 12px 8px;
      font-size: 12px;
    }
  }
}

/* 表格单元格样式 */
.username-cell {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: center;
}

.username-icon {
  color: $primary-color;
  font-size: 16px;
  flex-shrink: 0;
}

.username-text {
  font-weight: 600;
  color: $text-primary;
}

.nickname-cell {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: center;
}

.nickname-icon {
  color: $success-color;
  font-size: 14px;
  flex-shrink: 0;
}

.nickname-text {
  color: $text-regular;
}

.dept-cell {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: center;
}

.dept-icon {
  color: $warning-color;
  font-size: 14px;
  flex-shrink: 0;
}

.dept-text {
  color: $text-regular;
}

.mobile-cell {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: center;
}

.mobile-icon {
  color: $info-color;
  font-size: 14px;
  flex-shrink: 0;
}

.mobile-text {
  color: $text-regular;
  font-family: 'Courier New', monospace;
  font-size: 13px;
}

.status-cell {
  display: flex;
  justify-content: center;
  align-items: center;
}

.enhanced-switch {
  :deep(.el-switch__core) {
    background: $border-color;
    border-color: $border-color;

    &.is-checked {
      background: $primary-color;
      border-color: $primary-color;
    }
  }

  :deep(.el-switch__action) {
    background: white;
  }
}

.time-cell {
  display: flex;
  align-items: center;
  gap: 6px;
  justify-content: center;
  font-size: 12px;
  color: $text-secondary;
}

.time-icon {
  color: $text-secondary;
  font-size: 14px;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;

  @media (max-width: 768px) {
    flex-direction: column;
    gap: 4px;
  }
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  transition: all 0.3s ease;
  white-space: nowrap;

  &:hover {
    transform: scale(1.05);
  }

  .btn-icon {
    font-size: 12px;
  }

  @media (max-width: 768px) {
    padding: 4px 8px;
    font-size: 11px;
    justify-content: center;
  }

  &.edit-btn:hover {
    background: $primary-light;
    color: $primary-color;
  }

  &.more-btn:hover {
    background: rgba(103, 194, 58, 0.1);
    color: $success-color;
  }
}

.action-dropdown {
  .enhanced-dropdown {
    border-radius: $border-radius-small;
    box-shadow: $shadow-base;
    border: 1px solid $border-light;
    overflow: hidden;

    .dropdown-item {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 10px 16px;
      transition: all 0.3s ease;

      &:hover {
        background: $primary-light;
        color: $primary-color;
      }

      .dropdown-icon {
        font-size: 14px;
      }
    }
  }
}

/* 分页样式 */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding: 20px 24px;
  background: white;
  border-top: 1px solid $border-light;

  @media (max-width: 768px) {
    padding: 16px;
  }

  :deep(.el-pagination) {
    .el-pager li {
      border-radius: 6px;
      margin: 0 2px;
      transition: all 0.3s ease;

      &:hover {
        background: $primary-light;
        color: $primary-color;
      }

      &.is-active {
        background: $primary-color;
        color: white;
      }
    }

    .btn-prev,
    .btn-next {
      border-radius: 6px;
      transition: all 0.3s ease;

      &:hover {
        background: $primary-light;
        color: $primary-color;
      }
    }

    @media (max-width: 768px) {
      .el-pagination__sizes,
      .el-pagination__jump {
        display: none;
      }
    }
  }
}

/* 加载状态优化 */
:deep(.el-loading-mask) {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(2px);

  .el-loading-spinner {
    .path {
      stroke: $primary-color;
    }
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .account-wrapper {
    background: #374151;
    border-color: #4b5563;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  }

  .table-container,
  .pagination-wrapper {
    background: #374151;
  }

  .account-title {
    color: #f9fafb;
  }

  .username-text,
  .nickname-text,
  .dept-text,
  .mobile-text {
    color: #f9fafb;
  }

  .enhanced-table {
    :deep(.el-table__header) {
      th {
        background: #4b5563 !important;
        color: #f9fafb !important;
        border-bottom-color: #6b7280;
      }
    }

    :deep(.el-table__cell) {
      border-bottom-color: #4b5563;
    }
  }

  .enhanced-switch {
    :deep(.el-switch__core) {
      background: #6b7280;
      border-color: #6b7280;

      &.is-checked {
        background: #60a5fa;
        border-color: #60a5fa;
      }
    }
  }

  .action-dropdown {
    .enhanced-dropdown {
      background: #4b5563;
      border-color: #6b7280;

      .dropdown-item {
        color: #d1d5db;

        &:hover {
          background: rgba(96, 165, 250, 0.1);
          color: #60a5fa;
        }
      }
    }
  }
}

/* 响应式优化 */
@media (max-width: 480px) {
  .account-header {
    padding: 12px 16px;
  }

  .enhanced-table {
    :deep(.el-table__header) th {
      padding: 10px 6px;
      font-size: 12px;
    }

    :deep(.el-table__body) td {
      padding: 10px 6px;
      font-size: 11px;
    }
  }

  .pagination-wrapper {
    padding: 12px;
  }

  .username-text,
  .nickname-text,
  .dept-text {
    font-size: 12px;
  }

  .mobile-text {
    font-size: 11px;
  }
}
</style>
